//
//  ReadDocHistory.m
//  cactus
//
//  Created by li hongdan on 12-8-28.
//  Copyright (c) 2012年 ifeng. All rights reserved.
//

#import "ReadDocHistory.h"
static ReadDocHistory *readDocHistoryShareInstance=nil;
@implementation ReadDocHistory


- (id)init{
  self=[super init];
  if(self){
    
    NSString *save=[[self k_cacheUrl] stringByAppendingPathComponent:@"readHistory"];
    NSArray *array=nil;
    if([[NSFileManager defaultManager] fileExistsAtPath:save]){
      array=[NSArray arrayWithContentsOfFile:save];
    }
    if(array){
      theset=[NSMutableSet setWithArray:array];
    }else{
      theset=[[NSMutableSet alloc] init];
    }
    
    
  }
  return self;
}

+ (ReadDocHistory *)shareInstance{

  if (readDocHistoryShareInstance==nil) {
      readDocHistoryShareInstance=[[ReadDocHistory alloc] init];
  }
  return readDocHistoryShareInstance;
}

-(void)checkForSave{
  NSNumber *number=[[NSUserDefaults standardUserDefaults] objectForKey:@"readHistoryTime"];
  double diff=0;
  if (number) {
    diff=fabs([[NSDate date] timeIntervalSince1970]-[number doubleValue]);
  }
  if(diff>(60*60*6)){
    [theset removeAllObjects];
  }
  else if ((diff > 60*60*3) && ([theset count] > 150)){
    [theset removeAllObjects];
  }
  [self save];
}



- (void)readed:(NSString *)documentId{
  if (documentId && [documentId length]>0) {
    [theset addObject:documentId];
    
  }
}

- (BOOL)check:(NSString *)documentId{
  if (!documentId) {
    return NO;
  }
  return [theset containsObject:documentId];
}

- (NSArray *)allObjects{
  return [theset allObjects];
}
- (void)save{
  if (readDocHistoryShareInstance) {
    NSString *save=[[self k_cacheUrl] stringByAppendingPathComponent:@"readHistory"];
    
    if([[NSFileManager defaultManager] fileExistsAtPath:save]){
      [[NSFileManager defaultManager] removeItemAtPath:save error:nil];
    }
    [[readDocHistoryShareInstance allObjects] writeToFile:save atomically:YES];
    NSNumber *number=[NSNumber numberWithDouble:[[NSDate date] timeIntervalSince1970]];
    [[NSUserDefaults standardUserDefaults] setObject:number forKey:@"readHistoryTime"];
  }
}

@end
